﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace CellarDoor.Gui
{
    public class UiTextBox : UiControl
    {
        private UiScrollBar scrollBarH;
        private UiScrollBar scrollBarV;

        private Vector2 textPosition;
        private Vector2 textSize;

        public UiTextBox()
            : base()
        {
            SkinElementName = "Panel1";

            scrollBarH = new UiScrollBar();
            scrollBarV = new UiScrollBar();

            Controls.Add(scrollBarH);
            Controls.Add(scrollBarV);

            scrollBarH.BarStyle = BarStyle.Horizontal;
            scrollBarV.BarStyle = BarStyle.Vertical;
            scrollBarH.Dock = new Dock(AlignH.Left, AlignV.Bottom);
            scrollBarV.Dock = new Dock(AlignH.Right, AlignV.Top);
            scrollBarH.SlideBar.ValueChanged += new EventHandler(SlideBar_ValueChanged);
            scrollBarV.SlideBar.ValueChanged += new EventHandler(SlideBar_ValueChanged);
        }

        void SlideBar_ValueChanged(object sender, EventArgs e)
        {
            textPosition = this.PositionAbsolute;
            textPosition.X += this.Padding.Left;
            textPosition.Y += this.Padding.Top;

            float xPos = (textSize.X - (float)(Width - (Padding.Left + Padding.Right))) * scrollBarH.Value;
            float yPos = (textSize.Y - (float)(Height - (Padding.Top + Padding.Bottom))) * scrollBarV.Value;
            if (xPos > 0)
                textPosition.X -= xPos;
            if (yPos > 0)
                textPosition.Y -= yPos;
        }

        protected override void OnBoundsChanged()
        {
            scrollBarH.Width = Width - 12;
            scrollBarH.Height = 12;
            scrollBarV.Width = 12;
            scrollBarV.Height = Height - 12;
            base.OnBoundsChanged();
        }

        protected override void OnTextChanged()
        {
            if (Font != null)
            {
                textSize = Font.MeasureString(Text);
            }
            base.OnTextChanged();
        }

        protected override void DrawText(SpriteBatch spriteBatch)
        {
            if (Font != null && !String.IsNullOrEmpty(Text))
            {
                spriteBatch.DrawString(Font, Text, textPosition * ScaleFactorSize, TextColor,
                    0, Vector2.Zero, ScaleFactorSize, SpriteEffects.None, 0);
            }

            //base.DrawText(spriteBatch);
        }
    }
}
